package redis

import (
	"fmt"
	"github.com/go-redis/redis"
)

type redisAuth struct {
	operateClient redis.Client
	name          string
}

func NewRedisAuth(addr string, pwd string) (*redisAuth) {
	client, e := redisInit(addr, pwd)
	if e != nil {
		return nil
	}
	auth := &redisAuth{*client, "newRedisAuth"}
	return auth
}

func (rds *redisAuth) setDevicePwd(deviceId string, pwd string) {
	items := map[string]interface{}{}
	items["password"] = pwd
	var key = "user:" + deviceId
	rsp, e := rds.operateClient.HMSet(key, items).Result()
	if e != nil {
		return
	}
	fmt.Println(rsp)
}

func (rds *redisAuth) getDevicePwd(deviceId string) (pwd string) {
	var key = "user:" + deviceId
	var filed = "password"
	rsp, e := rds.operateClient.HGet(key, filed).Result();
	if e != nil {
		return ""
	}
	return rsp
}

func redisInit(addr string, pwd string) (*redis.Client, error) {
	redisdb := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: pwd,
		DB:       10,
		PoolSize: 10,
	})
	_, err := redisdb.Ping().Result()
	if err != nil {
		return nil, err
	} else {
		return redisdb, nil
	}
}
